﻿//获取和存储文件
var request = require('request'),
    https = require('https'),
    fs = require("fs");
    Log = require("./Log.js");


function getAndSaveFile(imgUrl, savePath, fileName) {
    Log.info("getAndSaveImg:" + imgUrl);
    try {
        https.get(imgUrl, function (res) {
            var imgData = "";

            res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

            res.on("data", function (chunk) {
                imgData += chunk;
            });

            try {
                res.on("end", function () {
                    fs.writeFile(savePath + fileName, imgData, "binary", function (err) {
                        if (err) {
                            Log.error(fileName + " down fail");
                        }
                        Log.info(fileName + " down success");
                    });

                });
            } catch (e) {
                Log.error("Download fail :" + imgUrl);
            }
        });
    } catch (e) {
        Log.error("DownLoad Fail :" + imgUrl);
        Log.info(e);
    }
}

module.exports = getAndSaveFile;